'''
@author: Aurelien Deharbe


This file is part of Cute-Server.

Cute-Server is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Cute-Server is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Cute-Server.  If not, see <http://www.gnu.org/licenses/>.
'''

from cuteserver import cserver
import multiprocessing
import select
import socket
import subprocess

def cuteserverbox(_port):
    
    mainserv = multiprocessing.Process(target = cserver.cserver, args = (5000,))
    mainserv.start()
    
    nb_procs = 0
    shcmd = ['ps -e | grep python | wc -l']
    p = subprocess.Popen(shcmd, shell=True, stdout=subprocess.PIPE)
    for line in p.stdout:
        nb_procs = int(line)
    p.wait()
    
    # opening server connection socket    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(('', _port))
    sock.listen(5)
    
    # sockets lookup tables
    s_table_qclient = {}
    s_table_qserver = {}
    
    # list for select
    rlist = [sock]
    
    while True:
        ready = select.select(rlist, [], [])
        
        for rs in ready[0]:
            
            # if rs is the server socket,
            # there is a new connection
            if rs == sock:
                clientin = sock.accept()[0]
                clientout = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                clientout.connect(('localhost', 5000))
                s_table_qclient[clientin] = clientout
                s_table_qserver[clientout] = clientin
                rlist.append(clientin)
                rlist.append(clientout)
                continue
            
            # read the command on the socket
            try:
                cmd = rs.recv(256)
            except socket.error:
                cmd = None
            
            # if empty command, disconnection
            if not cmd:
                if rs in s_table_qserver.keys():
                    c = s_table_qserver[rs]
                    rs.close()
                    c.close()
                    rlist.remove(s_table_qserver[rs])
                    rlist.remove(s_table_qclient[c])
                    del s_table_qserver[rs]
                    del s_table_qclient[c]
                else:
                    c = s_table_qclient[rs]
                    rs.close()
                    c.close()
                    rlist.remove(s_table_qclient[rs])
                    rlist.remove(s_table_qserver[c])
                    del s_table_qclient[rs]
                    del s_table_qserver[c]
                continue
            
            # if command comes from cuteserver,
            # this is just a return to pass to the client
            if rs in s_table_qserver.keys():
                s_table_qserver[rs].send(cmd)
                continue
            
            cmd = cmd.strip()
            
            # command matches "GetNumberOfSessions" ?
            if cmd == "GetNumberOfSessions":
                n = 0
                shcmd = ['ps -e | grep python | wc -l']
                p = subprocess.Popen(shcmd, shell=True, stdout=subprocess.PIPE)
                for line in p.stdout:
                    n = int(line)
                p.wait()
                n = n - nb_procs
                rs.send(str(n) + '\n')
                continue
            
            # if command doesn't match any debug command,
            # just relaying the command
            s_table_qclient[rs].send(cmd)
